//
//  ZZMessageItemCell.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/16.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZMessageItemCell.h"
#import "MWPhotoBrowser.h"
#import "UserInfoController.h"
#import "SVWebViewController.h"
#import "User.h"

@interface ZZMessageItemCell()<ZCTTMLEmojiLabelDelegate, TTTAttributedLabelDelegate>{
    NSString *orgin_url;
}

@end

@implementation ZZMessageItemCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [_labTitle setFont:FontFiftent];
    [_labTitle setTextColor:UIColorFromRGB(Text6Color)];
    [self styleLinkLabel:_labMessage];
    [_labMessage setText:@""];
    
    _labDesc.numberOfLines = 0;
    [_labDesc setTextColor:UIColorFromRGB(Text6Color)];
    [self styleLinkLabel:_labDesc];
    [_labDesc setFont:FontThirteen];
    
    [_labTime setFont:FontThirteen];
    [_labTime setTextColor:UIColorFromRGB(Text6Color)];
    
    [_btnReply.titleLabel setFont:FontThirteen];
    [_btnReply setTitleColor:UIColorFromRGB(Text6Color) forState:0];
    
    [_btnReply addTarget:self action:@selector(onReply:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _imgDot.layer.cornerRadius = 3.0f;
    _imgDot.layer.masksToBounds = YES;
    [_imgDot setBackgroundColor:UIColorFromRGB(BgRedColor)];
    
    [_imgAvatar setContentMode:UIViewContentModeScaleAspectFill];
    _imgAvatar.layer.cornerRadius = 22.0f;
    _imgAvatar.layer.masksToBounds = YES;
    [_imgAvatar addTapGestureRecognizerWithTarget:self action:@selector(userPageAction:)];
    
    DLog(@"title:----%@", NSStringFromCGRect(_labTitle.frame));
    DLog(@"image:---%@", NSStringFromCGRect(_imgAvatar.frame));
    
    [_imgDesc setContentMode:UIViewContentModeScaleAspectFill];
//    _imgDesc.layer.cornerRadius = 5.0f;
//    _imgDesc.layer.masksToBounds = YES;
}

-(void)onReply:(UIButton *) btn{
    if(self.delegate && [self.delegate respondsToSelector:@selector(onItemReply:)]){
        [self.delegate onItemReply:self.tempModel];
    }
}


-(void)dataToView:(MessageDetailEntity *)entity{
    self.tempModel = entity;
    
    _imgDot.hidden = YES;
    if(entity.mapping_read == 0){
        _imgDot.hidden = NO;
    }
    
    [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(entity.user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_labTime setText:entity.add_time];
    

    NSString *uname = convertToString(entity.user_info.user_name);
    
    NSInteger length = 0;
    if(convertToString(entity.user_info.user_name).length > 8){
        uname = [convertToString(entity.user_info.user_name) substringToIndex:8];
        uname = [NSString stringWithFormat:@"%@...",uname];
    }
    NSString *text = [NSString stringWithFormat:@"%@%@",uname,entity.content];
    NSMutableAttributedString *noteString = [[NSMutableAttributedString alloc] initWithString:text];
    [noteString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(TextSizeOneColor) range:NSMakeRange(0, uname.length)];
    [_labTitle setAttributedText: noteString];
    [_labTitle addTapGestureRecognizerWithTarget:self action:@selector(userPageAction:)];
    
    _labDesc.hidden = YES;
    _imgDesc.hidden = YES;
    
    MessageMappingEntity *contentEntity = entity.mapping_parent_info;
    if([@"like" isEqual:entity.type]){
        contentEntity = entity.mapping_info;
    }
    if(contentEntity){
        if(contentEntity.image){
            _imgDesc.hidden = NO;
            [_imgDesc sd_setImageWithURL:[NSURL URLWithString:convertToString(contentEntity.image.image_url)] placeholderImage:[UIImage imageNamed:@"default_image"]];
        }else{
            if(convertToString(contentEntity.message).length > 0){
                _labDesc.hidden = NO;
//                [_labDesc setText:contentEntity.message];
                [self addLinkMessage:_labDesc text:contentEntity.message];
            }else if(contentEntity.message_arr_1!=nil && contentEntity.message_arr_1.count>0){
                _labDesc.hidden = NO;
                [self addLinkMessage:_labDesc text:contentEntity.message_arr_1[0]];
            }
        }
    }
    
    CGRect mmf = _labMessage.frame;
    mmf.size.width = ScreenWidth - 110 - mmf.origin.x;
    mmf.size.height = 0;
    [_labMessage setFrame:mmf];
    if([@"at" isEqual:entity.type] || [@"comment" isEqual:entity.type] || [@"wall" isEqual:entity.type]){
       
        
        
        
        NSString *content = convertToString(entity.mapping_info.message);
        if(content.length > 0){
            _labMessage.hidden = NO;
        
            [self addLinkMessage:_labMessage text:content];
            CGSize s = [self autoWidthOfLabelHegith:_labMessage with:mmf.size.width];
            if(s.height < 21){
                CGRect mf = _labMessage.frame;
                mf.size.height = 21;
                _labMessage.frame = mf;
            }else{
                
    //            NSLog(@"%@",s);
            }
        }else{
            _labMessage.hidden = YES;
        }
    }else{
        _labMessage.hidden = YES;
        _btnReply.hidden = YES;
    }
    if ([@"wall" isEqual:entity.type]){
        _btnReply.hidden = YES;
    }
    
    [self autoWidthOfLabel:_labTime with:21];
    
    
    CGRect tf = _labTime.frame;
    CGRect rf = _btnReply.frame;
    
    if(_labMessage.hidden){
        tf.origin.y = CGRectGetMaxY(_labTitle.frame) + 5;
        rf.origin.x = CGRectGetMaxX(tf) + 5;
        rf.origin.y = tf.origin.y;
        _labTime.frame = tf;
        _btnReply.frame = rf;
        
        [self setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_imgDesc.frame)+10)];
    }else{
        tf.origin.y = CGRectGetMaxY(_labMessage.frame) + 5;
        rf.origin.x = CGRectGetMaxX(tf) + 5;
        rf.origin.y = tf.origin.y;
        _labTime.frame = tf;
        _btnReply.frame = rf;
        
        [self setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_labTime.frame)+10)];
    }
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}



- (void)userPageAction:(UITapGestureRecognizer *)tapGR
{
    UserInfoController *vc = [[UserInfoController alloc] init];
    vc.user_id = self.tempModel.user_info.user_id;
    if(self.delegate && [self.delegate respondsToSelector:@selector(onCellOpenClick:)]){
        [self.delegate onCellOpenClick:vc];
    }
}


/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

- (CGSize )autoWidthOfLabelHegith:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}




#pragma mark - gesture delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"ZCTTMLEmojiLabel"]) {
        return NO;
    }
    return YES;
    
}

-(ZCTTMLEmojiLabel *)styleLinkLabel:(ZCTTMLEmojiLabel *)label{
    [label setTextAlignment:NSTextAlignmentLeft];
    label.numberOfLines = 0;
    [label setFont:FontFiftent];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setLinkColor:UIColorFromRGB(TextLinkColor)];
    [label setDelegate:self];
    label.userInteractionEnabled = YES;
    
    return label;
}

-(void)addLinkMessage:(ZCTTMLEmojiLabel *) label text:(NSString *)text{
    text = [ZZCoreTools replaceMessageEmoji:text];
    NSString *sugguestText = [ZZCoreTools transformStringAt:text];
    NSMutableDictionary *sugguestDict = [label getTextADict:sugguestText];
    if(sugguestDict){
        label.text = sugguestDict[@"text"];
        NSArray *sugguestArr = sugguestDict[@"arr"];
        //    [_emojiLabel setText:tempText];
        for (NSDictionary *item in sugguestArr) {
            NSString *text = item[@"htmlText"];
            int loc = [item[@"realFromIndex"] intValue];
            // 一定要在设置text文本之后设置
            [label addLinkToURL:[NSURL URLWithString:item[@"url"]] withRange:NSMakeRange(loc, text.length)];
        }
    }else{
        label.text = text;
    }
}

// 链接点击
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    DLog(@"链接地址:%@",url.absoluteString);
    [self doLinkClick:url.absoluteString];
    
}

// 链接点击
-(void)ZCMLEmojiLabel:(ZCTTMLEmojiLabel *)emojiLabel didSelectLink:(NSString *)link withType:(ZCTTMLEmojiLabelLinkType)type{
    DLog(@"意外添加的：%@",link);
    [self doLinkClick:link];
}


-(void)doLinkClick:(NSString *) url{
    if([url hasPrefix:@"name://"]){
        return;
    }
    
    if([url hasPrefix:@"uid://"]){
        UserInfoController *vc = [[UserInfoController alloc] init];
        vc.user_id = [url stringByReplacingOccurrencesOfString:@"uid://" withString:@""];
        if(self.delegate && [self.delegate respondsToSelector:@selector(onCellOpenClick:)]){
            [self.delegate onCellOpenClick:vc];
        }
    }else{
        if([url hasPrefix:@"tel:"] || validateNumber(url)){
            NSString *callURL = [url stringByReplacingOccurrencesOfString:@"tel:" withString:@""];
            [[AlertUtil shareInstance] showAlert:nil message:callURL cancelTitle:@"取消" titleArray:@[@"呼叫"] viewController:(UIViewController *)self.delegate confirm:^(NSInteger buttonTag) {
                if(buttonTag == 0){
                    // 打电话
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callURL]];
                }
            }];
        }else if([url hasPrefix:@"mailto:"] || validateEmail(url)){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        }else{
            if (![url hasPrefix:@"https"] && ![url hasPrefix:@"http"]) {
                url = [@"https://" stringByAppendingString:url];
            }
            
            SVWebViewController *vc = [[SVWebViewController alloc] initWithURL:[NSURL URLWithString:url]];
            if(self.delegate && [self.delegate respondsToSelector:@selector(onCellOpenClick:)]){
                [self.delegate onCellOpenClick:vc];
            }
        }
    }
    
}





/**
 *  点击查看大图
 *
 *  @param
 */
-(void) imgTouchUpInside:(UITapGestureRecognizer *)recognizer{
    DLog(@"我怎么不处罚呢：");
    UIImageView *_picView = (UIImageView*)recognizer.view;
    NSMutableArray *photos = [NSMutableArray new];
    
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:convertToString(orgin_url)]];
    
    [photos addObject:photo];

    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithPhotos:photos];
    [browser setCurrentPhotoIndex:_picView.tag];
    browser.zoomPhotosToFill = YES;
    browser.displayNavArrows = NO;
    browser.navigationController.navigationBarHidden = YES;
    browser.displayActionButton = NO;
    //    browser.enableSwipeToDismiss = YES;
    if(_delegate && [self.delegate respondsToSelector:@selector(onCellOpenClick:)]){
        [self.delegate onCellOpenClick:browser];
    }
}

@end
